package com.atguigu.gmallre.mock.stage;


import com.atguigu.gmallre.mock.bean.CartInfo;
import com.atguigu.gmallre.mock.bean.FavorInfo;
import com.atguigu.gmallre.mock.bean.UserInfo;
import com.atguigu.gmallre.mock.config.AppConfig;
import com.atguigu.gmallre.mock.factory.UserSession;
import com.atguigu.gmallre.mock.log.AppMain;
import com.atguigu.gmallre.mock.service.CartInfoService;
import com.atguigu.gmallre.mock.service.FavorInfoService;
import com.atguigu.gmallre.mock.service.UserInfoService;
import com.atguigu.mock.util.RandomBox;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component("login")
public class LoginStage implements  Stage {
    @Override
    public boolean handle() {
        return true;
    }

    @Autowired
    RegisterStage registerStage;

    @Autowired
    UserInfoService userInfoService;

    @Autowired
    FavorInfoService favorInfoService;

    @Autowired
    CartInfoService cartInfoService;


    public boolean checkLogin(AppMain lastPageMain){
        if(UserSession.getUserInfo()==null){
            Integer noRegiRate = AppConfig.if_noregister_when_nologin_rate;
            RandomBox<Boolean> noRegiBox = new RandomBox<>( noRegiRate, 100 -noRegiRate);
            Boolean noRegi = noRegiBox.getRandBoolValue();
            if(noRegi){
                // 需要注册

                registerStage.register(lastPageMain);
            }else{
                //  抽取用户

                UserInfo userInfo = userInfoService.getOneByRandom();
                UserSession.setUserInfo(userInfo);
                UserSession.getAppCommon().setUid(userInfo.getId()+"");

                List<CartInfo> cartInfoList  = cartInfoService.list(new QueryWrapper<CartInfo>().eq("user_id",userInfo.getId()));
                UserSession.setCartList(cartInfoList);

                List<FavorInfo> favorInfoList = favorInfoService.list(new QueryWrapper<FavorInfo>().eq("user_id",userInfo.getId()));
                UserSession.setFavorList(favorInfoList);

            }
            return false;
        }
        return true;
    }
}
